import {Component, OnInit, ViewChild} from '@angular/core';
import {ModalDirective} from 'ngx-bootstrap';
import {AliyunOssOutputUrl} from '../../../../config/api';
import {AdOssUploadService} from '../../../lib/service/ad-oss-upload.service';
import {LocalStorageService} from '../../../lib/service/local-storage.service';
import {GoodsManageService} from './goods-manage-service';
import {GroupData} from '../../main';
@Component({
  selector: 'app-goods-manage',
  templateUrl: 'goods-manage.component.html',
  styleUrls: ['goods-manage.component.scss'],
  providers: [GoodsManageService]
})
export class GoodsManageComponent implements OnInit {

  tabs = 3;
  nowApplet: any;
  token: any;
  template_id: number;
  aliyunOssOutputUrl = AliyunOssOutputUrl;
  goodsList = [];  // 商品列表
  keyWordDlg: string;  // 添加商品..弹窗中，搜索的商品名字
  groupIdDlg = 0;  // 添加商品..弹窗中，选中的分组id
  statusDlg = '选择商品状态';  // 添加商品..弹窗中，选中的商品状态（上下架）
  checkedGoods = [];  // 选中的商品ID集合
  // isCheckedAll = false;  // 当前页是否选中所有
  allGoodsNum;  // 商品总量
  loadingShow = true;

  order = 'none';  // 排序方式
  groupData = new GroupData;
  groupList = [];
  goodsListDlg = [];      // 弹窗中所有的商品列表
  groupName = '全部商品';  // 当前分组名称
  groupID = 0;            // 当前分组ID
  groupRecommend: number;  // 当前分组是否被推荐到首页
  checkedGroup; // 选中的分组
  selfAdd = [];  // 自定义添加地区
  operateGoodId: number;  // 当前正在操作的商品ID

  groupId = 0; // 搜索栏中分组ID
  status = '';  // 当前列表商品的状态
  keyword: string;  // 搜索栏中商品名称

  type: string;
  message: string;
  isShow = false;
  img_file: any;
  img_name: string;
  img_url: string;
  totalItems: number;
  itemsPerPage = 12;
  currentPage = 1;
  totalItemsDlg: number;
  itemsPerPageDlg = 4;
  currentPageDlg = 1;

  @ViewChild('deleteModal') public deleteModal: ModalDirective;
  @ViewChild('addGoodsModal') public addGoodsModal: ModalDirective;
  @ViewChild('addGroupModal') public addGroupModal: ModalDirective;
  @ViewChild('goodsGroupModal') public goodsGroupModal: ModalDirective;

  constructor(private localStorageService: LocalStorageService,
              private goodsManageService: GoodsManageService,
              private adOssUploadService: AdOssUploadService) {
  }

  ngOnInit() {
    this.nowApplet = this.localStorageService.getNowApplet();
    this.token = this.localStorageService.getToken();
    this.template_id = this.nowApplet.template_id;
    this.getGroupList();
    this.getGoodsList(1);
  }

  changeTab(type: number) {
    this.tabs = type;
    if (type === 1) {
      this.currentPage = 1;
      this.groupID = 0;
      this.groupName = '全部商品';
      this.groupIdDlg = 0;
      this.keyWordDlg = '';
      this.order = 'none';
      this.status = '';
      this.statusDlg = '选择商品状态';
      this.getGroupList();
      this.getGoodsList(1);
    }
    if (type === 2) {
      // this.currentPage = 1;
      // this.groupIdDlg = 0;
      // this.keyWordDlg = '';
      // this.order = 'none';
      // this.status = '上架';
      // this.statusDlg = '下架';
      // this.getGoodsList(1, 0, this.status);
    }
    if (type === 3) {
      // this.operateName = '';
      // this.getShowcaseList();
      // this.showUnit = false;
    }
  }

  // 获取商品列表
  getGoodsList(page: number, applet_goods_category_id?: number, status?: string, order?: string, keyword?: string) {
    // this.goodsList = [];
    this.loadingShow = true;
    this.currentPage = null;
    this.goodsManageService.getGoodsList( page, 12, applet_goods_category_id, status, order, keyword).subscribe(
      res => {
        if (res.code === 2000) {
          setTimeout(
            () => {
              this.loadingShow = false;
            }
            ,500);
          const goodsList = res.data.data;
          const ids = [];
          this.currentPage = res.data.current_page;
          this.totalItems = res.data.total;
          goodsList.every((val, idx, array) => {
            ids.push(val.id);
            this.checkedGoods.every((val1, idx1, array1) => {
              if (val1 === val.id) {
                val.selected = true;
                return false;
              } else {
                val.selected = false;
                return true;
              }
            });
            // 获取该商品的分组
            /*this.goodsManageService.getGoodsGroup(val.id).subscribe(
             res1 => {
             const goodsGroup = [];
             if (!!res1.data) {
             res1.data.every((val1, idx1, array1) => {
             goodsGroup.push({name: val1.applet_goods_category[0].name, id: val1.applet_goods_category[0].id});
             return true;
             });
             }
             val.goods_category = goodsGroup;
             }
             );*/
            return true;
          });

          this.goodsManageService.getbindListAll(JSON.stringify(ids)).subscribe(
            res1 => {
              this.goodsList = goodsList;
              goodsList.every((val, idx, array) => {
                val.goods_category = [];
                res1.data.every((val1, idx1, array1) => {
                  if (val.id === val1.goods_id) {
                    val.goods_category.push({name: val1.name, id: val1.applet_goods_category_id});
                  }
                  return true;
                });
                return true;
              });
            }
          );
        } else {
          this.type = 'error';
          this.message = res.message;
          this.isShow = true;
        }
      }
    );
  }

  // 获取所有的商品列表，显示在弹框中
  getDlgGoodsList(page: number, applet_goods_category_id?: number, status?: string, keyword?: string, pagesize?: number) {
    const _pageSize = pagesize || 4;
    this.goodsManageService.getGoodsList(
      page, _pageSize,
      applet_goods_category_id,
      status,
      '',
      keyword
    ).subscribe(
      res => {
        if (res.code === 2000) {
          this.currentPageDlg = res.data.current_page;
          this.totalItemsDlg = res.data.total;
          this.goodsListDlg = res.data.data;
          const ids = [];
          this.goodsListDlg.every((val, idx, array) => {
            ids.push(val.id);
            this.checkedGoods.every((val1, idx1, array1) => {
              if (val1 === val.id) {
                val.selected = true;
                return false;
              } else {
                val.selected = false;
                return true;
              }
            });
            // 获取该商品的分组
            /*this.goodsManageService.getGoodsGroup(val.id).subscribe(
             res1 => {
             const goodsGroup = [];
             if (!!res1.data) {
             res1.data.every((val1, idx1, array1) => {
             goodsGroup.push({name: val1.applet_goods_category[0].name, id: val1.applet_goods_category[0].id});
             return true;
             });
             }
             this.groupListDlg[idx].goods_category = goodsGroup;
             }
             );*/
            return true;
          });
          this.goodsManageService.getbindListAll(JSON.stringify(ids)).subscribe(
            res1 => {
              this.goodsListDlg.every((val, idx, array) => {
                val.goods_category = [];
                res1.data.every((val1, idx1, array1) => {
                  if (val.id === val1.goods_id) {
                    val.goods_category.push({name: val1.name, id: val1.applet_goods_category_id});
                  }
                  return true;
                });
                return true;
              });
            }
          );
        } else {
          this.type = 'error';
          this.message = res.message;
          this.isShow = true;
        }
      }
    );
  }

  // 添加商品..弹框中的搜索与重置
  searchDlg() {
    this.getDlgGoodsList(1, this.groupIdDlg, this.statusDlg, this.keyWordDlg);
  }

  resetDlg() {
    this.keyWordDlg = '';
    this.groupIdDlg = 0;
    this.statusDlg = '选择商品状态';
    this.getDlgGoodsList(1);
  }

  // checkbox 框操作存储id
  selectedGoods(item) {
    if (!item.selected) {
      this.checkedGoods.push(item.id);
    } else {
      this.checkedGoods.every((val, idx, array) => {
        if (val === item.id) {
          this.checkedGoods.splice(idx, 1);
          return false;
        }
        return true;
      });
    }
  }

  // 添加商品至分组or上下架
  addGoodsInSubmit() {
    if (!this.checkedGoods.length) {
      this.type = 'info';
      this.message = '请至少选择一件商品';
      this.isShow = true;
      return false;
    }
    // 多个商品添加至一个分组
    const group = [];
    group.push(this.groupID);
    this.goodsManageService.goodBindGroup(this.checkedGoods, group).subscribe(
      res => {
        if (res.code === 2000) {
          this.type = 'success';
          this.message = '修改成功';
          this.isShow = true;
          this.addGoodsModal.hide();
          this.checkedGoods = [];
          this.getGroupList();
          this.currentPageDlg = 1;
          this.getGoodsList(1, this.groupID, this.status, this.order, this.keyword);
        } else {
          this.type = 'error';
          this.message = res.message;
          this.isShow = true;
        }
      }
    );

  }

  /* 商品分组管理 start  */

  // 选择排序方式
  changeOrder() {
    this.getGoodsList(1, this.groupID, this.status, this.order);
  }

  // 获取商品分组列表
  getGroupList() {
    this.goodsManageService.getGroupList().subscribe(
      res => {
        this.groupList = res.data.data;
        this.goodsManageService.getGoodsList(1, 999).subscribe(
          res1 => {
            this.allGoodsNum = res1.data.data.length;
          }
        );
        this.groupList.every((val, idx, array) => {
          this.goodsManageService.getGoodsList(1, 999, val.id).subscribe(
            res2 => {
              val.goodsNum = res2.data.data.length;
            }
          );
          return true;
        });
      }
    );
  }

  // 提交分组新建||编辑
  addGroup() {
    this.addGroupModal.show();
    this.groupData.id = null;
    this.groupData.sort = null;
  }

  addGroupSubmit() {
    this.groupData.applet_uuid = this.nowApplet.applet_uuid;
    if (!this.groupData.sort) {
      this.groupData.sort = 0;
    }
    if (!!this.groupData.id) {
      // 编辑
      this.goodsManageService.editGroup(this.groupData).subscribe(
        res => {
          if (res.code === 2000) {
            this.type = 'success';
            this.message = '修改成功';
            this.isShow = true;
            this.addGroupModal.hide();
            this.groupName = this.groupData.name;
            this.groupData.name = '';
            this.groupData.sort = 0;
            this.groupData.remark = null;
            this.getGroupList();
          } else {
            this.type = 'error';
            this.message = res.message;
            this.isShow = true;
          }
        }
      );
    } else {
      // 添加
      return this.goodsManageService.postAddGroup(this.groupData).subscribe(
        res => {
          if (res.code === 2000) {
            this.type = 'success';
            this.message = '添加成功';
            this.isShow = true;
            this.addGroupModal.hide();
            this.getGroupList();
            this.groupData.name = '';
            this.groupData.sort = null;
            this.groupData.remark = '';
          } else {
            this.type = 'error';
            this.message = res.message;
            this.isShow = true;
          }
        }
      );
    }
  }

  // 选择分组之后
  chooseGroup(id: number, name: string, recommend: number) {
    this.goodsList = [];
    this.currentPage = null;
    this.groupID = id;
    this.groupName = name;
    this.groupRecommend = recommend;
    this.order = 'none';
    this.getGoodsList(1, id);
  }

  // 确认删除分组
  delGroupSubmit() {
    this.goodsManageService.delGroup(this.groupID).subscribe(
      res => {
        if (res.code === 2000) {
          this.type = 'success';
          this.message = '删除成功';
          this.isShow = true;
          this.deleteModal.hide();
          this.getGroupList();
          this.groupID = 0;
          this.groupName = '全部商品';
          this.getGoodsList(1);
        } else {
          this.type = 'error';
          this.message = res.message;
          this.isShow = true;
        }
      }
    );
  }

  // 编辑分组
  editGroupDialog() {
    this.goodsManageService.getGroupDetail(this.groupID).subscribe(
      res => {
        if (res.code === 2000) {
          this.groupData = res.data;
          this.addGroupModal.show();
        } else {
          this.type = 'error';
          this.message = res.message;
          this.isShow = true;
        }
      }
    );
  }

  // 是否推荐到首页
  pushHome(T: number) {
    this.goodsManageService.getGroupDetail(this.groupID).subscribe(
      res => {
        if (res.code === 2000) {
          this.groupData = res.data;
          this.groupData.recommend = T;
          this.pushHomeSubmit(T);
        } else {
          this.type = 'error';
          this.message = res.message;
          this.isShow = true;
        }
      }
    );
  }

  pushHomeSubmit(T) {
    this.goodsManageService.editGroup(this.groupData).subscribe(
      res => {
        this.groupData.recommend = 0;
        if (res.code === 2000) {
          this.type = 'success';
          this.message = '操作成功';
          this.isShow = true;
          this.groupRecommend = T;
          this.getGroupList();
        } else {
          this.type = 'error';
          this.message = res.message;
          this.isShow = true;
        }
      }
    );
  }

  // 编辑商品的分组
  editGoodsGroup(data: any) {
    this.operateGoodId = data.id;
    if (!!data.goods_category) {
      this.selfAdd = JSON.parse(JSON.stringify(data.goods_category));
    } else {
      this.selfAdd = [];
    }
    this.goodsGroupModal.show();
  }

  // 添加
  addSelf() {
    let add = true;
    this.selfAdd.every((val, idx, array) => {
      if (val.id === this.checkedGroup.id) {
        add = false;
        return false;
      } else {
        return true;
      }
    });
    if (add) {
      this.selfAdd.push(this.checkedGroup);
    }
  }

  // 商品解绑分类
  goodsUnbind(goods_id: number) {
    const data = {goods_id: goods_id, applet_goods_category: this.groupID};
    this.goodsManageService.goodsUnbindGroup(data).subscribe(
      res => {
        if (res.code === 2000) {
          this.type = 'success';
          this.message = '操作成功';
          this.isShow = true;
          this.getGroupList();
          this.getGoodsList(1, this.groupID, this.statusDlg);
        } else {
          this.type = 'error';
          this.message = res.message;
          this.isShow = true;
        }
      }
    );
  }

  addGoodsInGroup() {
    this.addGoodsModal.show();
    this.getDlgGoodsList(1);
  }

  /* 商品分组管理 end */

  addGoodInGroups() {
    const group = [], goods = [];
    goods.push(this.operateGoodId);
    this.selfAdd.every((val, idx, array) => {
      group.push(val.id);
      return true;
    });
    this.goodsManageService.goodBindGroup(goods, group).subscribe(
      res => {
        if (res.code === 2000) {
          this.type = 'success';
          this.message = '操作成功';
          this.isShow = true;
          this.goodsGroupModal.hide();
          this.checkedGoods = [];
          this.getGroupList();
          this.getGoodsList(1, this.groupID, this.status, this.keyword);
        } else {
          this.type = 'error';
          this.message = res.message;
          this.isShow = true;
        }
      }
    );
  }

  allGoodsPageChanged(event: any): void {
    this.getGoodsList(event.page, this.groupID, this.status, this.order, this.keyword);
  }

  dlgPageChanged(event: any): void {
    this.getDlgGoodsList(event.page, this.groupIdDlg, this.statusDlg, this.keyWordDlg);
  }
}
